package com.bbyb.operating.examination.handler;

import com.bbyb.operating.examination.exception.ServiceException;
import com.bbyb.operating.examination.model.vo.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.http.HttpStatus;

/**
 * 全局异常处理类
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理未知异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public CommonResult<Object> handleUnknownException(Exception e) {
        log.error("发生未知错误：{}", e.getMessage(), e);
        return new CommonResult<>(HttpStatus.INTERNAL_SERVER_ERROR.value(), "发生未知错误", false, null);
    }

    /**
     * 处理请求方式不支持异常
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    public CommonResult<Object> handleMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.error("请求方式不支持：{}", e.getMessage(), e);
        return new CommonResult<>(HttpStatus.METHOD_NOT_ALLOWED.value(), "请求方式不支持", false, null);
    }

    /**
     * 处理服务异常
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public CommonResult<Object> handleServiceException(ServiceException e) {
        log.error("服务异常：{}", e.getMessage(), e);
        return new CommonResult<>(HttpStatus.BAD_REQUEST.value(), e.getMessage(), false, null);
    }

    // 其他异常处理方法可以仿照上面的方法来实现，根据具体业务需要处理不同类型的异常。
}
